<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    #wrap {
      width: 600px;
      height: 400px;
      background: #ccc;
      border: 1px solid red;
      margin: 20px auto;
      position: relative;
      overflow: hidden;
    }

    .send_wrap {
      width: 600px;
      height: 400px;
      margin: 20px auto;
    }

    #wrap p {
      position: absolute;
      left: 0;
      white-space: nowrap;
    }
  </style>
</head>

<body>
  <div id="wrap">

  </div>
  <div class="send_wrap">
    昵称： <input type="text" id="nikename"> <input type="text" id="txt"> <input type="color" id="colors"> <button
      id="btn">发送弹幕</button>
  </div>
  <script>
    //  1.连接ws服务器
    var ws = new WebSocket("ws://169.254.184.38:4000");
    ws.onopen = function () {  //2.监控ws服务器连接事件
      console.log("连接到ws服务器")
    }


    var wrap = document.getElementById("wrap");
    var colors = document.getElementById("colors");
    // 4.监听后端返回数据
    ws.onmessage = function (msg) {
      console.log(msg)
      var data = JSON.parse(msg.data)  //接受webscoket返回的数据
      console.log(data)
      var p = document.createElement("p");
      p.innerHTML = data.nikename + ": " + data.txt;
      p.style.top = Math.floor(Math.random() * 300) + "px";
      p.style.color = data.color;
      var lefts = 0; //动态改变左定位
      wrap.appendChild(p);
      setInterval(() => {
        lefts += 1;
        p.style.left = lefts + "px"
        if (lefts > 550) {
          wrap.removeChild(p)
        }
      }, 10);
    }


    // 给ws服务器发送数据
    var btn = document.getElementById("btn");//发送按钮
    var txt = document.getElementById("txt");//输入框
    var nikename = document.getElementById("nikename")

    function fasong() { //发送弹幕
      // 3,调用webscoket的发送数据方法send
      ws.send(JSON.stringify({
        txt: txt.value,
        color: colors.value,
        nikename: nikename.value
      }))
    }

    btn.onclick = throttle(fasong, 5000)

    // 节流函数
    function throttle(fn, delay) {
      let valid = true
      return function () {
        if (!valid) {
          //休息时间 暂不接客
          return false
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false
        setTimeout(() => {
          fn()
          valid = true;
        }, delay)
      }
    }

  </script>
</body>

</html>